<template>
  <div class="member_management_wrapper">
    <div class="main_page">
      <!-- 左边 -->
      <div class="left_part">
        <!-- 输入框 -->
        <el-input
          @input="handleLeftInputChange()"
          style="width: 95%"
          placeholder="请输入中心编号或名称搜索"
          v-model="leftInputValue"
          size="mini"
        >
          <i class="el-icon-search el-input__icon" slot="prefix"> </i>
        </el-input>
        <!-- 树形结构 -->
        <div class="treeTitle">中心列表</div>
        <el-tree
          ref="treeRef"
          :data="treeData"
          :props="defaultProps"
          :highlight-current="true"
          node-key="id"
          @node-click="handleClickTree"
          style="margin-top: 12px"
          default-expand-all
        ></el-tree>
      </div>
      <!-- 右边 -->
      <div class="right_part">
        <div class="search_part">
          <el-input
            style="margin-right: 12px; margin-left: 12px; width: 20%"
            placeholder="人员名称"
            v-model="rightInputValue"
            size="mini"
          ></el-input>
          <el-button style="margin-right: 12px" type="primary" size="mini" icon="el-icon-search" @click="handleSearch()"
            >查询</el-button
          >
          <el-button style="margin-right: 12px" size="mini" icon="el-icon-refresh" @click="handleReset()"
            >重置</el-button
          >
          <el-button style="margin-right: 12px" type="primary" size="mini" icon="el-icon-plus" @click="handleAdd()"
            >新增</el-button
          >
          <el-button type="primary" size="mini" icon="el-icon-circle-plus-outline" @click="handleAddBatch()"
            >批量新增</el-button
          >
        </div>
        <div class="table_part">
          <el-table :data="tableData" :header-cell-style="{ background: 'rgba(117, 60, 202, 0.04)' }" :stripe="true">
            <el-table-column align="center" label="序号" type="index"></el-table-column>
            <el-table-column align="center" label="人员名称" prop="nickname"></el-table-column>
            <el-table-column align="center" label="角色" prop="roleList">
              <template v-slot="{ row }">
                <span style="margin-right: 3px" v-for="item in row.roleList" :key="item.id">
                  {{ item.name + '(' + item.code + ')' }}
                </span>
              </template>
            </el-table-column>
            <el-table-column align="center" label="类型" prop="type"></el-table-column>
            <el-table-column align="center" label="操作">
              <template v-slot="{ row }">
                <el-button size="mini" icon="el-icon-edit" @click="handleEdit(row)">编辑</el-button>
                <el-button size="mini" icon="el-icon-delete" type="danger" @click="handleDelete(row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-row type="flex" justify="end" style="margin-top: 24px">
            <el-pagination
              @current-change="handleCurrentChange($event)"
              :current-page="pageParams.pageNo"
              :page-size="pageParams.pageSize"
              layout="total,prev, pager, next, jumper"
              :total="pageParams.total"
            >
            </el-pagination>
          </el-row>
        </div>
      </div>
    </div>
    <!-- 新增和编辑弹窗 -->
    <el-dialog :visible="addDiaVis" title="新增" @close="handleAddDiaCancel()" width="600px">
      <el-form ref="formRef" :rules="formRules" :model="formData" label-width="100px">
        <!-- 中心名称 -->
        <el-form-item prop="coreIds" label="中心名称：" v-if="isBatch">
          <el-select
            placeholder="请选择中心"
            multiple
            size="mini"
            v-model="formData.coreIds"
            style="width: 80%"
          >
            <el-option
              v-for="item in coreIdsOptions"
              :key="item.id"
              :label="item.hospitalName"
              :value="item.id"
            ></el-option>
          </el-select>
          <el-button type="primary" size="mini" @click="handleCoreNameSelectAll">全选</el-button>
        </el-form-item>
        <!-- 新增人员选择 -->
        <el-form-item prop="userId" label="人员：" v-if="!isEdit">
          <MemberRollingSelect
            :value="formData.userId"
            :width="80"
            @change="onRollingSelectChange($event)"
          ></MemberRollingSelect>
        </el-form-item>
        <el-form-item prop="roleId" label="角色：">
          <el-select v-model="formData.roleId" style="width: 80%" size="mini">
            <el-option
              v-for="item in roleOptions"
              :key="item.value"
              :label="item.label + '(' + item.code + ')'"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleAddDiaCancel()" size="mini">取 消</el-button>
        <el-button type="primary" @click="handleAddDiaConfirm()" size="mini">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import MemberRollingSelect from './components/member-rolling-select.vue'
import { mapActions } from 'vuex'
export default {
  name: 'member-management',
  components: {
    MemberRollingSelect,
  },
  data() {
    return {
      leftInputValue: '',
      treeData: [],
      // 中心id
      coreId: null,
      defaultProps: {
        children: 'children',
        label: 'coreName',
      },
      rightInputValue: '',
      tableData: [],
      addDiaVis: false,
      formData: {
        userId: '',
        userIds: '',
        roleId: '',
        coreIds: [],
      },
      formRules: {
        userId: [
          {
            required: true,
            message: '请选择',
            trigger: 'blur',
          },
        ],
        coreIds: [
          {
            required: true,
            message: '请选择',
            trigger: 'blur',
          },
        ],
        roleId: [
          {
            required: true,
            message: '请选择',
            trigger: 'blur',
          },
        ],
      },
      // 页码参数
      pageParams: {
        pageNo: 1,
        pageSize: 10,
        total: null,
      },
      isEdit: false,
      isBatch: false,
      roleOptions: [],
      editParams: {},
      projectId: '',
      projectDatabaseId: '',
      coreIdsOptions: [],
    }
  },
  created() {
    this.projectId = localStorage.getItem('sys-project-id') || ''
    this.projectDatabaseId = localStorage.getItem('project-database-Id') || ''
    this.getCentralList()
    this.getRolesName()
  },
  methods: {
    ...mapActions('centralManagement', [
      'configMemberManagementAPI',
      'getCentralListAPI',
      'getMemberManagementAPI',
      'removeMemberManagementAPI',
      'updateCoreUserAPI',
    ]),
    ...mapActions('roleManage', ['getRoleDataAPI']), // 增加projectId
    // 获取角色下拉框选项
    getRolesName() {
      const params = {
        projectId: this.projectId,
      }
      this.getRoleDataAPI({ params }).then(res => {
        const { data, code } = res
        if (code === 200) {
          this.roleOptions = data.records.map(item => {
            return {
              label: item.name,
              value: item.id,
              code: item.code,
            }
          })
          this.pageParams.total = data.total
        }
      })
    },
    // 获取中心列表数据
    async getCentralList() {
      const params = {
        projectId: this.projectId,
        projectDatabaseId: this.projectDatabaseId,
        nameOrCode: this.leftInputValue,
      }
      const res = await this.getCentralListAPI({ params })
      this.treeData = res.data
      this.coreIdsOptions = res.data
      this.$nextTick(() => {
        this.$refs.treeRef.setCurrentKey(this.treeData[0].id, true)
      })
      this.coreId = this.treeData[0].id
      this.getMemberManagement()
    },
    // 左输入框改变
    handleLeftInputChange() {
      this.getCentralList()
    },
    // 点击树形
    handleClickTree(obj) {
      this.coreId = obj.id
      this.getMemberManagement()
    },
    // 获取右表格数据
    async getMemberManagement() {
      const params = {
        ...this.pageParams,
        projectId: this.projectId,
        projectDatabaseId: this.projectDatabaseId,
        coreId: this.coreId,
        username: this.rightInputValue,
      }
      const res = await this.getMemberManagementAPI({ params })
      this.tableData = res.data.records
      this.pageNo = res.data.current
      this.total = res.data.total
    },
    // 点击搜索
    handleSearch() {
      this.pageParams.pageNo = 1
      this.pageParams.pageSize = 10
      this.getMemberManagement()
    },
    // 点击重置
    handleReset() {
      this.rightInputValue = ''
      this.pageParams.pageNo = 1
      this.pageParams.pageSize = 10
      this.pageParams.total = null
      this.getMemberManagement()
    },

    // 中心名称全选
    handleCoreNameSelectAll() {
      console.log('coreIdsOptions', this.coreIdsOptions)
      this.coreIdsOptions.map((cItem, cIndex) => {
        this.formData.coreIds.push(cItem.id)
      })
    },

    // 点击新增
    handleAdd() {
      this.addDiaVis = true
      this.isEdit = false
      this.isBatch = false
    },
    // 点击批量新增
    handleAddBatch() {
      this.addDiaVis = true
      this.isEdit = false
      this.isBatch = true
    },
    // 点击编辑
    handleEdit(row) {
      this.addDiaVis = true
      this.isEdit = true
      this.isBatch = false
      this.editParams.id = row.id
      row.roleList.forEach(item => {
        this.formData.roleId = item.id
      })
    },
    // 点击删除
    async handleDelete(row) {
      const data = {
        userIds: [row.id],
        coreId: this.coreId,
        projectId: this.projectId,
        projectDatabaseId: this.projectDatabaseId,
      }
      const res = await this.removeMemberManagementAPI({
        data,
      })
      if (res.code === 200) {
        this.$message.success('删除成功')
        const pageLastOne =
          this.pageParams.total % this.pageParams.pageSize === 1 &&
          Math.floor(this.pageParams.total / this.pageParams.pageSize) === this.pageParams.pageNo - 1
        if (pageLastOne) {
          if (this.pageParams.pageNo !== 1) {
            this.pageParams.pageNo = this.pageParams.pageNo - 1
          }
        }
        this.getMemberManagement()
      }
    },
    // 页码变化
    handleCurrentChange(currentPage) {
      this.pageParams.pageNo = currentPage
      this.getMemberManagement()
    },
    // 公共关闭
    publicCloseAdd() {
      this.$refs.formRef.resetFields()
      this.addDiaVis = false
      this.formData.userId = ''
      this.formData.userIds = ''
      this.formData.roleId = ''
      this.formData.coreIds = []
    },

    // 新增取消
    handleAddDiaCancel() {
      this.publicCloseAdd()
    },

    // 新增确认
    async handleAddDiaConfirm() {
      await this.$refs.formRef.validate()
      let data = {}
      if (!this.isEdit) {
        this.formData.userIds = [this.formData.userId]
        // 批量新增
        if (this.isBatch) {
          data = {
            ...this.formData,
            projectId: this.projectId,
            projectDatabaseId: this.projectDatabaseId,
          }
          // 普通新增
        } else {
          data = {
            ...this.formData,
            projectId: this.projectId,
            projectDatabaseId: this.projectDatabaseId,
            coreIds: [this.coreId],
          }
        }
        const res = await this.configMemberManagementAPI({ data })
        if (res.code === 200) {
          this.getMemberManagement()
          this.publicCloseAdd()
        }
        // 编辑
      } else if (this.isEdit) {
        const data = {
          coreId: this.coreId,
          projectId: this.projectId,
          userId: this.editParams.id,
          roleId: this.formData.roleId,
        }
        const res = await this.updateCoreUserAPI({ data })
        if (res.code === 200) {
          this.getMemberManagement()
          this.publicCloseAdd()
          this.$message.success('修改成功！')
        }
      }
    },
    // 输入下拉框选择
    onRollingSelectChange(obj) {
      this.formData.userId = obj.value
    },
  },
}
</script>

<style lang="scss" scoped>
.member_management_wrapper {
  background-color: $white;
  height: calc(100% - 24px);
  padding: 12px;

  .main_page {
    display: flex;
    .left_part {
      width: 450px;
      .treeTitle {
        margin-top: 12px;
        font-size: 16px;
        font-weight: bold;
        color: #2c3f51;
        border-left: 5px solid #753cca;
        padding-left: 12px;
      }
    }
    .right_part {
      flex: 1;
      height: 100%;
      border-left: 1px solid #f0f0f0;

      .search_part {
        margin-bottom: 12px;
      }
    }
  }
}
</style>
